package ncku.account.event;

import java.awt.BorderLayout;
import com.toedter.calendar.*;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;

import ncku.account.data.GlobalData;
import ncku.account.gui.categorySel;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;

public class PieChart extends JPanel implements ActionListener {

	private static JPanel bigP;
	private JPanel buttonP;
	private JButton btn1, btn2;
	private static JComboBox cateSel;
	private static int tt;
	private static JDateChooser startdate,enddate;
	
	public PieChart() {
		setLayout(new BorderLayout()); //set layout
		bigP = new JPanel();
		bigP.setLayout(new BorderLayout());
		btn1 = new JButton("Date");
		btn1.addActionListener(this);
		btn2 = new JButton("Categories");//button for different input for pie chart
		btn2.addActionListener(this);
		startdate = new JDateChooser("yyyy/MM/dd","####/##/##",'_');//date chooser
		enddate = new JDateChooser("yyyy/MM/dd","####/##/##",'_');
		buttonP = new JPanel();
		cateSel = new JComboBox(categorySel.getCategoriesList());
		cateSel.addItem("ALL");
		cateSel.setSelectedItem("ALL");
		buttonP.setLayout(new FlowLayout());
		buttonP.add(new JLabel("start"));
		buttonP.add(startdate);
		buttonP.add(new JLabel("end"));
		buttonP.add(enddate);
		buttonP.add(cateSel);
		buttonP.add(btn1);
		buttonP.add(btn2);
		buttonP.setVisible(true);
		bigP.add(buttonP, BorderLayout.NORTH);
		bigP.setVisible(true);
		add(bigP, BorderLayout.CENTER);
		setPreferredSize (new Dimension (681, 422));
		setVisible(true);

		// TODO Auto-generated constructor stub
	}
	
	private static JFreeChart createChart(PieDataset dataset) {
	        
        JFreeChart chart = ChartFactory.createPieChart( //create pie chart
            GlobalData.accountName,  // chart title
            dataset,             // data
            true,               // include legend
            true,
            false
        );

        PiePlot plot = (PiePlot) chart.getPlot(); //plot settings
        plot.setLabelFont(new Font("SansSerif", Font.PLAIN, 12));
        plot.setNoDataMessage("No data available");
        plot.setCircular(false);
        plot.setLabelGap(0.02);
        return chart;
        
    }

	private static PieDataset createDataset() {
	    DefaultPieDataset dataset = new DefaultPieDataset();
	    String[] categories = new String [GlobalData.getTransactionNumber()];
	    double[] amount = new double [GlobalData.getTransactionNumber()];
	    int index,length = 0;
	    double temp;
	    DateFormat df = new SimpleDateFormat("yyyy/mm/dd");
	    cateSel.getSelectedIndex();
	    if (tt==1) { //for date inputc
			for (int i = 0; i < GlobalData.getTransactionNumber(); i++){
				try {
					if (df.parse(GlobalData.getTransaction(i).getDate()).before(startdate.getDate())) continue; //check date
					if (df.parse(GlobalData.getTransaction(i).getDate()).after(enddate.getDate())) continue; //check date
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (!cateSel.getSelectedItem().equals("ALL") && !(GlobalData.getTransaction(i).getCategory().equals((String)cateSel.getSelectedItem()))) continue;
				index = -1;
				for (int j = 0; j < length; j++) { //check if the date included in categories[]
					if (categories[j].equals(GlobalData.getTransaction(i).getDate())) {
						index = j;
					}
				}
				if (index == -1) {//if not included
					categories[length] = GlobalData.getTransaction(i).getDate(); //include date
					amount[length] = Double.parseDouble(GlobalData.getTransaction(i).getStringAmount()); //new amount
					length++;
					
				} else {//if included
					temp = Double.parseDouble(GlobalData.getTransaction(i).getStringAmount()); //get amount
					amount[index] += temp; //add amount
				}
			}
	    } else if (tt==2) { //for categories input
	    	for (int i = 0; i < GlobalData.getTransactionNumber(); i++){
				index = -1;
				try {
					if (df.parse(GlobalData.getTransaction(i).getDate()).before(startdate.getDate())) continue; //check if in the request date
					if (df.parse(GlobalData.getTransaction(i).getDate()).after(enddate.getDate())) continue; //check if in the request date
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (!cateSel.getSelectedItem().equals("ALL") && !(GlobalData.getTransaction(i).getCategory().equals((String)cateSel.getSelectedItem()))) continue;
				for (int j = 0; j < length; j++) {
					if (categories[j].equals(GlobalData.getTransaction(i).getCategory())) { // check if the category exist before
						index = j;
					}
				}
				if (index == -1) { //if didn't exist before
					categories[length] = GlobalData.getTransaction(i).getCategory(); //new categories
					amount[length] = Double.parseDouble(GlobalData.getTransaction(i).getStringAmount()); //new amount
					length++;
					
				} else { //if exist
					temp = Double.parseDouble(GlobalData.getTransaction(i).getStringAmount()); //get amount
					amount[index] += temp; //add amount
				}

			}
	    }
		
		for (int i = 0; i < length; i++) {
			dataset.setValue(categories[i], amount[i]); //set the value into dataset
		}
	    
	    return dataset;        
	}
	
	private static JPanel createPanel() { //return panel with pie chart
        JFreeChart chart = createChart(createDataset());
        return new ChartPanel(chart);
    }

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		bigP.removeAll(); //clear panel
		bigP.add(buttonP, BorderLayout.NORTH); //add button panel
		if (e.getSource() == btn1) { //use different input for show pie
			tt = 1 ; 
		} else if (e.getSource() == btn2) {
			tt = 2;
		}
		bigP.add(createPanel(), BorderLayout.CENTER); //add the pie chart panel
		bigP.getRootPane().revalidate(); //refresh the panel
	}
}
